define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;
                var defaultToolbar = ['filter']
                if (Config.hasExportPermission) {
                    defaultToolbar.push('exports');
                }
                var dataCount = 0;
                let q = {}
			    location.search.replace(/([^?&=]+)=([^&]+)/g,function(_,k,v){q[k]=v});
                var filter = {}
                if (q.createtime) {
                    var ctime = decodeURIComponent(q.createtime);
                    $('#createtime').val(ctime)
                    filter.createtime = ctime
                }
                if (q.type) {
                    filter.type = q.type
                }
                var isReloading = false; // 标志位，防止重复加载
                table.render({
                    elem: '#table'
                    ,url:'kuerp/customers/index'
                    ,where:filter
                    ,parseData: function(res){ //res 即为原始返回的数据
                        return {
                            "code": 0, //解析接口状态
                            "msg": '', //解析提示文本
                            "count": res.total, //解析数据长度
                            "data": res.rows //解析数据列表
                         };
                    }
                    ,toolbar: '#thisToolbar' //开启头部工具栏，并为其绑定左侧模板
                    ,height: 'full-180'
                    ,page: true
                    ,limit: layui.data('table-customers')['pagesize'] || 50
                    ,limits: [10,20,30,50,100,150, 200]
                    ,defaultToolbar: defaultToolbar
                    ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    ,cols: [[
                        {checkbox: true},
                        {field: 'customer_name', title: __('Customer_name'), operate: 'LIKE', minWidth:220, align:'left',templet : function (d) {
                                return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                    "data-url='kuerp/customers/detail/ids/"+d.id+"' data-title='客户详情' data-area=[\"80%\",\"80%\"] >" + d.customer_name + "</a>";
                            }},
                        {field: 'customertype_id', title: __('Customertype.type_name'),templet: function (d) {
                                if(d.customertype.type_name!=null){
                                    return d.customertype.type_name;
                                }else{
                                    return '';
                                }
                            }},
                        {field: 'customerlevel_id', title: __('Customerlevel_id'),templet: function (d) {
                                if(d.customerlevel.name!=null){
                                    return d.customerlevel.name;
                                }else{
                                    return '';
                                }
                            }},
                        {field: 'customer_code', title: __('客户编号'), operate: 'LIKE',},
                        
                        {field: 'saler', title: __('Saler'),templet: function (d) {
                                if(d.saler.name!=null){
                                    return d.saler.name;
                                }else{
                                    return '';
                                }
                            }},
                        {field: 'connet_name', title: __('Connet_name'), operate: 'LIKE'},
                        {field: 'customer_mobile', title: __('Customer_mobile'), operate: 'LIKE', minWidth:130},
                        {field: 'customer_phone', title: __('Customer_phone'), operate: 'LIKE', hide:true},
                        {field: 'qq_wx_email', title: __('Qq_wx_email'), operate: 'LIKE', hide:true},
                        {field: 'need_receive_account', title: __('Need_receive_account'), operate:'BETWEEN'},
                        // {field: 'getgoods_address', title: __('Getgoods_address'), operate: 'LIKE'},
                        {field: 'mergename', title: __('Mergename'), operate: false, hide:true},
                        {field: 'address', title: __('Address'), operate: 'LIKE',templet: function (d) {
                            return d.address;
                        }, minWidth:150},
                        {field: 'room', title: __('Room'), operate: false, hide:true},
                        {field: 'note', title: __('Note'), operate: 'LIKE', hide:true},
                        {field: 'collaborators_name', title: __('Collaborator')},
                        {field: 'last_follow_time', title: __('Last_follow_time'), operate:'RANGE', addclass:'datetimerange',templet: function (d) {
                            return d.last_follow_time > 0 ? layui.util.toDateString(d.last_follow_time*1000,"yyyy-MM-dd HH:mm") : '';
                        },minWidth:120},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange',templet: function (d) {
                            return d.createtime > 0 ? layui.util.toDateString(d.createtime*1000,"yyyy-MM-dd HH:mm") : '';
                        },minWidth:120},
                        {field: 'status', title: __('Status'),templet: function (d) {
                                if(d.status==1){
                                    return '<input type="checkbox" data-id="'+d.id+'" checked="" name="open" lay-skin="switch" lay-filter="switchList" lay-text="正常|禁用">'
                                }else{
                                    return '<input type="checkbox" data-id="'+d.id+'" name="open" lay-skin="switch" lay-filter="switchList" lay-text="正常|禁用">'
                                }
                            }},
                        {fixed: 'right', title:__('Operate'), toolbar: '#barDemo', width:150}
                    ]],
                    done: function(res, curr, count){
                        dataCount = count
                        // 添加表格列对齐样式
                        $('.layui-table').find('[align="left"]').css('text-align', 'left');
  
                        tableColFilterAndWidth('table-customers', this)
                        layui.data('table-customers', {key: 'pagesize',value:this.limit});
                    }
                });
                //本地记录字段显示及宽度情况
                function tableColFilterAndWidth(dataKey, obj) {
                    // 初始化筛选状态
                    var local = layui.data(dataKey);
                    layui.each(obj.cols[0], function(index, item) {
                        if (item.field) {
                            var hide_key = item.field + '_hide';
                            var width_key = item.field + '_width';
                            if (hide_key in local) {
                                item.hide = local[hide_key];
                            }
                            if (width_key in local) {
                                item.width = local[width_key];
                            }
                        }
                    });
                    // 重新渲染表格以应用新的列配置
                    // 防止重复加载
                    if (!isReloading) {
                        isReloading = true;
                        table.reload('table', {cols: obj.cols})
                    }
                    //记录筛选状态
                    obj.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function(){
                        var input = $(this).prev()[0];
                        var key = input.name+'_hide';
                        console.log('LAY_TABLE_TOOL_COLS', key, input.checked)
                        layui.data(dataKey, {key: key,value: input.checked})
                    });
                    obj.elem.next().on('mouseup', 'th', function(){
                        var field = $(this).data('field')
                        var width = $(this).children('.layui-table-cell').css('width').replaceAll('px','');
                        field = field+'_width';
                        console.log('mouseup', field, width)
                        layui.data(dataKey, {key: field,value:width})
                    })
                }
                layui.form.on('switch(switchList)', function (obj) {
                    var onoff = this.checked ? '1' : '0';
                    var id = $(this).data('id');
                    $.ajax( {
                        url: "kuerp/customers/multi",
                        type: "POST",
                        data:{
                            'ids':id,
                            'params':"status="+onoff,
                        },
                        success: function(res){
                            if(res.code==0){
                                Toastr.error(res.msg);
                            }else{
                                Toastr.success('操作成功');
                            }
                        }
                    });
                });
                //头工具栏事件
                table.on('toolbar(table)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            Fast.api.open("kuerp/customers/add", "添加", {
                               callback:function(value){
                                  Controller.api.bindevent();
                               },
                                area:['75%','75%']
                            });
                        break;
                        case 'delAll':
                            var data = checkStatus.data;
                            var ids = '';
                            $(data).each(function (k,v) {
                                ids+=v.id+',';
                            });
                            if(data.length<=0){
                                Toastr.error('请选择要删除的数据');return;
                            }
                            Layer.confirm(
                                __('Are you sure you want to delete the %s selected item?', data.length),
                                {icon: 3, title: __('Warning'), shadeClose: true},
                                function (index) {
                                    Fast.api.ajax("kuerp/customers/del?ids="+ids, function () {
                                        $('.btn-refresh').click();
                                    },'',true);
                                    Layer.close(index);
                                }
                            );
                        break;
                        case 'import':
                            Fast.api.open("kuerp/customers/import", "导入", {
                                callback:function(value){
                                    Controller.api.bindevent();
                                }
                            });
                        break;
                        case 'changestaff':
                            var data = checkStatus.data;
                            var ids = [];
                            if(data.length<=0){
                                Toastr.error('请选择要转移的客户');return;
                            }
                            $(data).each(function (k,v) {
                                ids.push(v.id);
                            });
                            ids = ids.join(',');
                           Controller.changestaffHtml(ids,1)
                        break;
                        case 'export':
                            // 获取选中的行 ID
                            var ids = table.checkStatus('table').data.map(function(item) {
                                return item.id;
                            });
                            // 获取当前页的数据
                            var page = table.cache['table'];
                            var filter = JSON.stringify(getSearch())
                            var op = JSON.stringify(getOp())
                            Layer.confirm("请选择导出的选项", {
                                title   : '导出数据',
                                btn     : ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + dataCount + "条)"],
                                success : function (layero, index) {
                                    $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                                }, yes   : function (index, layero) {
                                    if (ids.length == 0) {
                                        Layer.alert('数据为空');
                                        return true;
                                    }
                                    $.post('kuerp/customers/export', {ids : ids.join(","), isall : 1}, function (res) {
                                        if(res.code == 1){
                                            Layer.alert(res.msg);
                                            window.location.href = res.data.filePath;
                                            Layer.close(index);
                                            $.ajax({
                                                url: "kuerp/customers/export",
                                                data: { user_path: res.data.filePath},
                                                type: "post",
                                                success: function() {
                                                    console.log('File deleted successfully!');
                                                }
                                            });
                                        }else{
                                            Layer.alert(res.msg);
                                        }
                                    }, 'json');
                                    return false;
                                },
                                btn2    : function (index, layero) {
                                    if (page.length == 0) {
                                        Layer.alert('数据为空');
                                        return true;
                                    }
                                    var ids = [];
                                    $.each(page, function (i, j) {
                                        ids.push(j.id);
                                    });
                                    $.post('kuerp/customers/export', {ids : ids.join(","), isall : 2}, function (res) {
                                        if(res.code == 1){
                                            Layer.alert(res.msg);
                                            window.location.href = res.data.filePath;
                                            Layer.close(index);
                                            $.ajax({
                                                url: "kuerp/customers/export",
                                                data: { user_path: res.data.filePath},
                                                type: "post",
                                                success: function() {
                                                    console.log('File deleted successfully!');
                                                }
                                            });
                                        }else{
                                            Layer.alert(res.msg);
                                        }
                                    }, 'json');
                                    return false;
                                },
                                btn3    : function (index, layero) {
                                    if (page.length == 0) {
                                        Layer.alert('数据为空');
                                        return true;
                                    }
                                    $.post('kuerp/customers/export?filter='+filter+'&op='+op, {ids : ids.join(","), isall : 3}, function (res) {
                                        if(res.code == 1){
                                            Layer.alert(res.msg);
                                            window.location.href = res.data.filePath;
                                            Layer.close(index);
                                            $.ajax({
                                                url: "kuerp/customers/export",
                                                data: { user_path: res.data.filePath},
                                                type: "post",
                                                success: function() {
                                                    console.log('File deleted successfully!');
                                                }
                                            });
                                        }else{
                                            Layer.alert(res.msg);
                                        }
                                    }, 'json');
                                    return false;
                                }
                            })
                            break;
                    }
                });
                function reloadTable(){
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1
                        }
                    });
                }
                //监听行工具事件
                table.on('tool(table)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'del'){
                        var that = this;
                        var top = $(that).offset().top - $(window).scrollTop();
                        var left = $(that).offset().left - $(window).scrollLeft() - 260;
                        if (top + 154 > $(window).height()) {
                            top = top - 154;
                        }
                        if ($(window).width() < 480) {
                            top = left = undefined;
                        }
                        Layer.confirm(
                            __('Are you sure you want to delete this item?'),
                            {icon: 3, title: __('Warning'),offset: [top, left], shadeClose: true},
                            function (index) {
                                $.ajax( {
                                    url: "kuerp/customers/del",
                                    type: "POST",
                                    data:{'ids':data.id},
                                    success: function(res){
                                        if(res.code==1){
                                            Toastr.success('操作成功');
                                            setTimeout(function () {
                                                $('.btn-refresh').click();
                                            },1000)
                                        }else{
                                            Toastr.error(res.msg);
                                        }
                                    }
                                });
                                Layer.close(index);
                            }
                        );
                    } else if(obj.event === 'edit'){
                        Fast.api.open("kuerp/customers/edit?ids="+data.id, "编辑",{ area:['75%','75%']});
                    }
                });
                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,page: {
                            curr: 1
                        }
                    });
                });
                function getSearch() {
                    var search = {};
                    var customertype_id = $('#customertype_id').val();
                    if(customertype_id!=''){
                        search.customertype_id = customertype_id;
                    }
                    var customer_name = $('#customer_name').val();
                    if(customer_name!=''){
                        search.customer_name = customer_name;
                    }
                    var customer_mobile = $('#customer_mobile').val();
                    if(customer_mobile!=''){
                        search.customer_mobile = customer_mobile;
                    }
                    var staff_member_id = $('#staff_member_id').val();
                    if(staff_member_id!=''){
                        search.staff_member_id = staff_member_id;
                    }
                    var createtime = $('#createtime').val();
                    if(createtime!=''){
                        search.createtime = createtime;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.customer_name = 'LIKE';
                    op.customer_mobile = 'LIKE';
                    op.createtime = 'RANGE';
                    return op;
                }
            });
            Controller.api.bindevent();
        },
        tabledetail:{
            record: function () {
                //跟进记录
                var table6 = $("#records");
                // 初始化表格
                table6.bootstrapTable({
                    url          : 'kuerp/customers/detail?id='+Config.idinfo.id+'&type=record',
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_records",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'admin.nickname', title: __('跟进人')},
                            {field: 'follow_type', title: __('跟进类型')},
                            {field: 'follow_time', title: __('跟进时间')},
                            {field: 'follow', title: __('跟进状态')},
                            {field: 'content', title: __('跟进内容')},
                            {field: 'next_time', title: __('下次跟进时间')},
                            {
                                field     : 'operate',
                                title     : __('Operate'),
                                table     : table6,
                                events    : Table.api.events.operate,
                                formatter : Table.api.formatter.operate,
                                buttons   : [
                                    {
                                        name      : '详情',
                                        text      : __('详情'),
                                        classname : 'records btn-dialog',
                                        url       : 'kuerp/record/detail',
                                        callback: function (data) {
                                            $('.btn-success').trigger('click');
                                        },

                                    },
                                    // {
                                    //     name      : '评论',
                                    //     text      : __('评论'),
                                    //     classname : 'records btn-dialog',
                                    //     url       : 'kuerp/customer/comment/add',
                                    //     callback: function (data) {
                                    //     },
                                    //     visible: function (row) {
                                    //         if(Config.idinfo.operation_team =='update'){
                                    //             return false;
                                    //         }
                                    //         //返回true时按钮显示,返回false隐藏
                                    //         return true;
                                    //     },
                                    //
                                    // }
                                ]
                            }
                        ]
                    ]
                });
                // 为表格1绑定事件
                Table.api.bindevent(table6);
            },
            basic: function () {
            },
            //联系人
            contacts: function () {
                var table = $("#table-contacts");
                // 初始化表格
                table.bootstrapTable({
                    url          : 'kuerp/customers/detail?id='+Config.idinfo.id+'&type=contacts',
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_contacts",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {
                                field : 'first_connect_name', title : '联系人名称', fixedColumns : true,operate:'like'
                            },
                            {field : 'first_connect_mobile', title : '手机号'},
                            {field : 'job', title : '职务'},
                            {field : 'connect_address', title : '联系地址'},
                            {field : 'email', title : '邮箱'},
                            {field: 'is_first', title: __('首要联系人'),formatter : function (value, row, index) {
                                if(value == 1){return '是'}else{return '否'}
                            }},
                            {field: 'createtime', title: __('创建时间'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        ]
                    ]
                });
                Table.api.bindevent(table);
            },
            //费用
            settings5: function () {
                var table5 = $("#consume");
                // 初始化表格
                table5.bootstrapTable({
                    url          : 'kuerp/customer/customer/get_consume' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_consume",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'number', title: __('报销单号'), operate:false, formatter : function (value, row, index) {

                                    return "<a href='javascript:void(0);' class='btn-dialog'  data-shade=\"0.3\"\n" +
                                        "data-url=\"kuerp/customer/consume/detail?ids=" + row.id+
                                        "\" data-title=\"费用详情\" ' >" + value + "</a>";
                                }},
                            {field: 'submit_date', title: __('消费日期'), operate: '=', addclass: 'datetimepicker',data:"data-date-format=\" YYYY-MM-DD\""},

                            {field: 'money', title: __('消费金额')},
                            {field: 'check_status', title: __('审批状态'), formatter: Table.api.formatter.status,  searchList: {0: __('待审核'), 1: __('审核中'), 2: __('审核通过'), 3: __('审核拒绝'), 4: __('撤销'), 5: __('草稿')},custom: {0: 'gray', 1: 'gray',2: 'success', 3: 'danger', 4: 'danger', 5: 'danger'}},
                            {field: 'remark', title: __('备注')},
                            {field: 'staff.name', title: __('创建人'),operate:false},
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                        ]
                    ]
                });
                Table.api.bindevent(table5);
            },
            //合同
            settings1: function () {
                var table1 = $("#contract");
                // 初始化表格
                table1.bootstrapTable({
                    url          : 'kuerp/customers/detail?id='+Config.idinfo.id+'&type=goods_sales',
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_contract",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    totalRow     : true,
                    cellMinWidth: 100, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                    columns      : [
                        [
                            {field: 'purchase_time', title: __('单据日期'),formatter: function (value, row, index) {
                                    return value ? layui.util.toDateString(value*1000,"yyyy-MM-dd") : '';
                                },width:110},
                            {field: 'purchase_code', title: __('单据编号'), operate: 'LIKE',minWidth:170,formatter : function (value, row, index) {
                                    return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='kuerp/goods_sales/detail/ids/"+row.id+"' data-title='订单详情' data-area=[\"90%\",\"90%\"] >" + value + "</a>";
                                }},
                            {field: 'sale_user_name', title: __('销售员')},
                            {field: 'number', title: __('数量'),formatter: function (value) {
                                    return value || 0;
                                }},
                            {field: 'goods_money', title: __('产品总金额'),formatter: function (value, row, index) {
                                    return  Math.round((row.money_tax_price + row.back_money) * 100) / 100;
                                },totalRow:true, minWidth:120},
                            {field: 'all_money', title: __('销售金额'),formatter: function (value, row, index) {
                                    return row.money_tax_price|| 0;
                                },totalRow:true, minWidth:120},
                            {field: 'back_money', title: __('返款金额'),formatter: function (value, row, index) {
                                    return value|| 0;
                                },totalRow:true, minWidth:120},
                            {field: 'pay_money', title: __('已收款金额'),formatter: function (value, row, index) {
                                    return value || 0;
                                },totalRow:true, minWidth:120},
                            {field: 'nopay_money', title: __('未回款金额'),formatter: function (value, row, index) {
                                    return Math.round((row.real_money - row.pay_money) * 100) / 100;
                                },totalRow:true, minWidth:120},
                            {field: 'pay_status', title: __('收款状态'),formatter: function (value, row, index) {
                                    if(value==0){
                                        return __('未收款');
                                    }else if(value==1){
                                        return __('全部收款');
                                    }else if(value==2){
                                        return __('部分收款');
                                    } else {
                                        return '';
                                    }
                                }},
                            {field: 'serials', title: __('锁编码')},
                            {field: 'examine_id', title: __('审核人'),formatter: function (value, row, index) {
                                    if(row.examine.username!=null){
                                        return row.examine.nickname || row.examine.username;
                                    }else{
                                        return '';
                                    }
                                }},
                            // {field: 'examine_status_texts', title: __('审核状态'), operate:'eq', searchList: {"1":__('已审核'),"0":__('待审核'),"2":__('审核拒绝')}, formatter: Table.api.formatter.tag},
                            {field : 'examine_status', title : '状态', formatter : Table.api.formatter.status,
                                searchList : {0 : '待审核', 1 : '已审核', 2 : '审核拒绝'}},
                            // {field: 'note', title: __('Note'),width:110},
                        ]
                    ]
                });

                Table.api.bindevent(table1);
            },
            //回款计划
            settings2: function () {
                //回款记录
                layui.config({
                    base: '/assets/addons/kuerp/layui/module/'
                }).extend({
                    tableMerge: 'tableMerge'
                });
                //回款记录
                layui.use(['table','upload','form','tableMerge'], function(){
                    var table = layui.table;
                    tableMerge = layui.tableMerge;

                    table.render({
                        elem: '#receivables'
                        ,url          : 'kuerp/customers/detail?id='+Config.idinfo.id+'&type=collection'
                        ,parseData: function(res){ //res 即为原始返回的数据
                            return {
                                "code": 0, //解析接口状态
                                "msg": '', //解析提示文本
                                "count": res.total, //解析数据长度
                                "data": res.rows, //解析数据列表
                            };
                        }
                        ,pk          : 'id',
                        sortName     : 'id'
                        ,toolbar: false //开启头部工具栏，并为其绑定左侧模板
                        // ,height: 'full-180'
                        ,page: true
                        ,limit: 10
                        ,limits: [10,20,30,50,100,150, 200]
                        ,cellMinWidth: 100 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        ,totalRow: true,
                        // ,defaultToolbar: defaultToolbar,
                        cols: [[
                            {field: 'purchase_code', title: __('单据编号'), merge:true,width:140},
                            {field: 'purchase_time', title: __('回款时间'),merge:['purchase_code'],width:120},
                            {field: 'customers_id', title: __('客户'), merge:['purchase_code'],minWidth:150},
                            {field: 'accounts_id', title: __('结算账户')},
                            {field: 'money', title: __('收款金额')},
                            {field: 'moneys', title: __('收款合计'), merge:['purchase_code']},
                            {field: 'write_off', title: __('本次核销金额'), merge:['purchase_code'],width:120},
                            {field: 'staff_member', title: __('收款人'), merge:['purchase_code']},
                            {field: 'remarks', title: __('备注'), merge:['purchase_code'],hide:true},
                            {field: 'createtime', title: __('创建时间'), merge:['purchase_code'],minWidth:120}
                        ]],
                        done: function(res, curr, count){
                            tableMerge.render(this);
                        }
                    });
                })
                Controller.api.bindevent();
            },
            //相关团队
            team: function () {
                var tableteam = $("#table_team");
                tableteam.bootstrapTable({
                    url          : 'kuerp/customer/customer/getteam' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_team",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field : 'img', title : '头像', formatter: Table.api.formatter.image},
                            {field : 'name', title : '员工姓名'},
                            {field : 'post', title : '员工角色'},
                            {field : 'roles', title : '团队角色'},
                            {field : 'is_edit', title : '权限'},
                            {field: 'operate', title: __('Operate'), table: tableteam, events: Table.api.events.operate, formatter: Table.api.formatter.buttons,
                                buttons: [
                                    {
                                        text: __('修改'),
                                        title: __('修改'),
                                        extend:'data-area=["400px","300px"]',
                                        classname: 'btn-dialog',
                                        url: 'kuerp/customer/customer/editteam/customer_id/{customer_id}',
                                        visible: function (row) {
                                            if(row.roles == '负责人'){
                                                return false;
                                            }
                                            if(Config.idinfo.operation_team =='update' || Config.idinfo.operation =='read'){
                                                return false;
                                            }
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        }
                                    },
                                    {
                                        text: __('删除'),
                                        title: __('删除'),
                                        classname: 'btn-ajax',
                                        refresh:true,
                                        confirm: '确认发送',
                                        extend:'data-area=["80%","80%"]',
                                        url: 'kuerp/customer/customer/delteam/customer_id/{customer_id}/staff_id/{id}',
                                        visible: function (row) {
                                            if(row.roles == '负责人'){
                                                return false;
                                            }
                                            if(Config.idinfo.operation_team =='update'){
                                                return false;
                                            }
                                            //返回true时按钮显示,返回false隐藏
                                            return true;
                                        },
                                    },
                                ]
                            }
                        ]
                    ]
                });
                // 为表格绑定事件
                Table.api.bindevent(tableteam);
            },
            //附件
            settings3: function () {
                var tablefiles = $("#files");
                tablefiles.bootstrapTable({
                    url          : 'kuerp/customer/customer/get_file' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_files",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field : 'name', title : '附件名称'},
                            {field : 'size', title : '附件大小'},
                            {
                                field : 'file_path', title : '文件预览', events : Table.api.events.image, formatter : Table.api.formatter.image, operate : false
                            },
                            {
                                field : 'file_path', title : '下载',formatter : function (value, row, index) {
                                    if(value ==''){
                                        value = '无';
                                    }
                                    return "<a href='"+value+"' download='' >点击下载</a>";
                                }
                            },

                        ]
                    ]
                });
                // 为表格绑定事件
                Table.api.bindevent(tablefiles);
            },
            //操作日志
            settings4: function () {
                var table7 = $("#operation_log");
                // 初始化表格
                table7.bootstrapTable({
                    url          : 'kuerp/customers/detail?id='+Config.idinfo.id+'&type=operation_log',
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_log",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    escape:false,
                    columns      : [
                        [
                            {field: 'admin.nickname', title: __('员工')},
                            {field: 'content', title: __('内容'),cellStyle:function (value,row,index,field) {
                                    return {
                                        css: {
                                            "min-width": "150px",
                                            "white-space": "nowrap",
                                            "text-overflow": "ellipsis",
                                            "overflow": "hidden",
                                            "max-width":"300px",
                                            'cursor':"pointer"
                                        }
                                    };
                                },formatter:function (value,row,index,field) {
                                    var span=document.createElement('span');
                                    span.setAttribute('title',value);
                                    span.innerHTML = value;
                                    return span.outerHTML;
                                }
                            },
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                        ]
                    ]
                });
                Table.api.bindevent(table7);
            },
            //签到记录
            settings6: function () {
                var table8 = $("#sign");
                table8.bootstrapTable({
                    url: 'kuerp/customers/detail?id='+Config.idinfo.id+'&type=sign',
                    pk: 'id',
                    sortName: 'id',
                    toolbar: "#toolbar_sign",
                    operate: false,
                    commonSearch: false,
                    search: false,
                    visible: false,
                    showColumns: false,
                    showExport: false,
                    showToggle: false,
                    columns: [
                        [
                            {field: 'location', title: '地理位置', formatter: Controller.api.formatter.map, operate: false},
                            {field: 'staffmember.name', title: __('创建人')},
                            {field: 'relation_process', title: __('关联进度')},
                            {
                                field: 'createtime',
                                title: __('创建时间'),
                                operate: 'RANGE',
                                addclass: 'datetimerange',
                                formatter: Table.api.formatter.datetime
                            },
                        ]
                    ]
                });
                Table.api.bindevent(table8);
            },
            //商机
            settings7: function () {
                var table = $("#business");
                // 初始化表格
                table.bootstrapTable({
                    url          : 'kuerp/customer/customer/get_business?customer_id=' + Config.idinfo.id,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_business",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {
                                field : 'name', title : '商机名称', fixedColumns : true, formatter : function (value, row, index) {
                                    if(value ==''){
                                        value = '无';
                                    }
                                    if(Config.idinfo.operation =='read'){
                                        return value;
                                    }
                                    return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-business-detail'>" + value + "</a>";
                                }
                            },
                            {field : 'money', title : '商机金额'},
                            {field : 'expect_time', title : '预计成交时间',operate: 'RANGE', addclass: 'datetimerange'},
                            {field : 'next_time', title : '下次联系时间',operate: 'RANGE', addclass: 'datetimerange'},
                            {field : 'type', title : '商机阶段', formatter : Table.api.formatter.status,
                                searchList : {0 : '初期沟通', 1 : '立项跟踪', 2 : '方案/报价', 3 : '谈判审核', 4 : '赢单', 5 : '输单', 6 : '无效'}},
                            {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                        ]
                    ]
                });
                Table.api.bindevent(table);
            },
            // 报价单
            quote:function (){
                var tablequote = $("#table-quote");
                tablequote.bootstrapTable({
                    url          : 'kuerp/customer/customer/get_quote' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_quote",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {field: 'number',title: '报价单编号',fixedColumns: true,operate: "like",
                                formatter: function (value, row, index) {

                                    return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-quote-detail'>" + value + "</a>";
                                }
                            },
                            {field : 'quote_date', title : '报价时间'},
                            {field : 'discount_amount', title : '优惠金额'},
                            {field : 'quote_amount', title : '报价金额'},
                            {field : 'status', title : '报价状态', formatter : Table.api.formatter.status,
                                searchList : {0 : '进行中', 1 : '转化成功', 9 : '作废'},operate:false},
                            {field : 'check_status', title : '审核状态', formatter : Table.api.formatter.status,
                                searchList : {0 : '待审核', 1 : '审核中', 2 : '审核通过', 3 : '审核未通过', 4 : '撤销', 5 : '草稿(未提交)',9:'作废'},operate:false},
                            {field : 'create_staff.name', title : '创建人'},
                        ]
                    ]
                });
                Table.api.bindevent(tablequote);
            },
            // 公司产品
            product:function (){
                var tablepro = $("#table-product");
                tablepro.bootstrapTable({
                    url          : 'kuerp/customer/customer/get_product' + location.search,
                    pk           : 'id',
                    sortName     : 'id',
                    toolbar:"#toolbar_product",
                    operate      : false,
                    commonSearch : false,
                    search       : false,
                    visible      : false,
                    showColumns  : false,
                    showExport   : false,
                    showToggle   : false,
                    columns      : [
                        [
                            {
                                field : 'product.name', title : '产品名称', fixedColumns : true, formatter : function (value, row, index) {
                                    if(!value){
                                        return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-customer-product-detail'>产品已删除</a>";
                                    }
                                    return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-customer-product-detail'>" + value + "</a>";
                                },operate:false
                            },
                            {field : 'product.unit', title : '产品单位'},
                            {field : 'product.img', title : '产品图', formatter: Table.api.formatter.image,events: Table.api.events.image},
                            {field : 'status', title : '产品状态', formatter : Table.api.formatter.status,
                                searchList : {0 : '待发货', 1 : '发货中', 2 : '待安装', 3 : '安装成功',4:'旧机维修'},operate:false},
                            {field : 'number', title : '设备编号'},
                            {field : 'contracts.money', title : '合同金额'},
                            {field : 'pay_date', title : '购买时间'},
                            {field : 'over_date', title : '质保到期时间'},
                        ]
                    ]
                });
                Table.api.bindevent(tablepro);
            },


        },
        detail : function (){
            // 初始化表格参数配置
            Table.api.init({});
            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.length > 0) {
                    Controller.tabledetail[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");
            $(document).on('click','.btn-edit',function () {
				var id=$('#ids').val();
				Fast.api.open("kuerp/customers/edit?ids="+id, "客户编辑",{
					shadeClose : false,
					shade      : [0.3, '#393D49'],
					area:["95%","95%"],
					callback:function () {
						parent.location.reload()
					}
				});

			}).on('click',".btn-del",function(){//删除
				var id=$('#ids').val();
				Layer.confirm('确定删除当前客户吗？', {
					btn: ['确定','取消'],
					title: '提示',
				},function(index, layero){
					Fast.api.ajax("kuerp/customers/del?ids="+id,function(data,ret){
						if(ret.code == 1){
							Layer.close(index);
							parent.location.reload();
						}
					},function(data,ret){
					});

				});
			}).on('click',".btn-change",function(){//转移客户
				var id=$('#ids').val();
				Controller.changestaffHtml(id, 2)
			})

            Controller.api.bindevent();
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent(false);
        },
        import: function () {
            $(document).on("click", ".step-btn_btn", function(){
                var rel = $(this).data('rel');
                $('.ui_buttons').hide();
                $('.step_'+rel).show();
                $('.step-item').hide();
                $('#import-'+rel).show();

                $('.steps-ul').find('li').removeClass('step1-cur');
                $('.steps-ul').find('li').removeClass('step2-cur');
                $('.steps-ul').find('li').removeClass('step3-cur');
                if(!$('.step1-base').hasClass('step1-nol')){
                    $('.step1-base').addClass('step1-nol');
                }
                if(!$('.step2-base').hasClass('step2-nol')){
                    $('.step2-base').addClass('step2-nol');
                }
                if(!$('.step3-base').hasClass('step3-nol')){
                    $('.step3-base').addClass('step3-nol');
                }
                $('.'+rel+'-base').addClass(rel+'-cur');
            });
            $(document).on("click", ".btn-close", function(){
                parent.layer.closeAll()
            });
            $(document).on("click", ".finish_btn", function(){
                parent.layer.closeAll();
                parent.location.reload();
            });
            $(document).on("click", ".chk", function(){
                if(!$(this).hasClass('checked')){
                    $(this).addClass('checked');
                }else{
                    $(this).removeClass('checked');
                }
                if($('.quantity').hasClass('checked')){
                    $('#quantityStorage').show();
                }else{
                    $('#quantityStorage').hide();
                }
            });


            layui.use(['upload'], function(){
                upload = layui.upload;
                upload.render({
                    elem: '#upfile'
                    ,url: 'ajax/upload'
                    ,done: function(res, index, upload){ //上传后的回调
                        if(res.code==1){
                            var editstatus = $("input[name='editstatus']:checked").val();
                            $.ajax( {
                                url: "kuerp/customers/import",
                                type: "POST",
                                data:{
                                    'editstatus':editstatus,
                                    'file':res.data.url,
                                },
                                success: function(res){
                                    if(res.code==1){
                                        $('#addMsg').html(res.msg.add+'条');
                                        $('#updateMsg').html(res.msg.update+'条');
                                        Toastr.success('导入成功');
                                    }else{
                                        Toastr.error(res.msg);
                                    }
                                }
                            });
                        }else{
                            Toastr.error(res.msg);
                        }
                    }
                    ,accept: 'file' //允许上传的文件类型
                    ,size: 50000 //最大允许上传的文件大小
                });
            });
            Controller.api.bindevent();
        },
        //转移客户
        changestaffHtml: function(ids, type = 1) {
            var saleList = Config.saleList;
            var html = '<form id="ser_form" style="width:80%" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">\n' +
                '        <div class="form-group" style="margin-top:20px">\n' +
                '            <label class="control-label col-xs-12 col-sm-4">新负责人:</label>\n' +
                '            <div class="col-xs-12 col-sm-8">\n' +
                '                   <select id="change-staff_member_id" class="form-control selectpicker" name="change_staff_member_id" data-required="true">\n';
            for (var a=1;a<=saleList.length;a++){
                html += '             <option value="'+saleList[a-1].id+'">'+saleList[a-1].name+'</option>\n';
            }
            html += '                </select>\n' +
                '                    <label style="font-weight:500;margin-top:15px"><input type="checkbox" name="changeorder[]" value="1" checked style="width:14px;height:14px;margin-right:5px">同时转移客户下的订单</label>\n' +
                '            </div>\n' +
                '        </div>\n' +
                '\n' +
                '    </form>';
            layer.open({
                type: 1,
                title: (type == 1 ? '批量' : '')+'转移客户',
                shadeClose: true,
                shade: false,
                maxmin: true, //开启最大化最小化按钮
                area: ['550px', '500px'],
                content: html,
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var change_staff_member_id = $('#change-staff_member_id').val();
                    var obj = document.getElementsByName('changeorder[]');
                    var check_val = [];
                    for (var i = 0; i < obj.length; i++) {
                        if (obj[i].checked) {
                            check_val.push(obj[i].value);
                        }
                    }
                    var changeorder = check_val.length == 1 ? 1 : 0;
                    console.log('change_staff_member_id', change_staff_member_id,changeorder )
                    layer.closeAll();
                    $.ajax( {
                        url: "kuerp/customers/changestaff",
                        type: "POST",
                        data:{ids:ids,'staff_member_id':change_staff_member_id,changeorder:changeorder},
                        success: function(res){
                            console.log('res', res);
                            if(res.code==1){
                                location.reload()
                            }else{
                                Toastr.error(res.msg);
                            }
                        }
                    });
                },
                btn2: function(index, layero){
                    //按钮【按钮二】的回调
                    layer.close(index);
                }
            });
        },
        api: {
            bindevent: function (reloadStatus=true) {
                layui.use('laydate', function(){
                    var laydate = layui.laydate;
                    //执行一个laydate实例
                    laydate.render({
                        elem: '#c-account_time',
                    });
                    laydate.render({
                        elem: '#createtime',
                        type: 'datetime',
                        range: true
                    });
                });
                $(document).on("click", ".del", function(){
                    $(this).parents('tr').remove();
                });
                $(document).on("click", ".add", function(){
                    var obj = $(this).parents('tr');
                    var html = '<tr>\n' +
                        '                <td><div class="btn"><span class="add"><i class="fa fa-plus"></i></span><span class="del"><i class="fa fa-trash"></i></span></div></td>\n' +
                        '                <td><div><input type="text" name="user[name][]"><input type="hidden" name="user[id][]" value=""></div></td>\n' +
                        '                <td><div><input type="text" name="user[mobile][]"></div></td>\n' +
                        '                <td><div><input type="text" name="user[phone][]"></div></td>\n' +
                        '                <td><div><input type="text" name="user[qqnum][]"></div></td>\n' +
                        '                <td><div><input type="text" name="user[job][]"></div></td>\n' +
                        '                <td><div><input type="text" name="user[address][]"></div></td>\n' +
                        '                <td><div><select name="user[first][]"><option value="0">否</option><option value="1">是</option></select></div></td>\n' +
                        '            </tr>';
                    $(obj).after(html);
                });
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    if(reloadStatus){
                        parent.location.reload();
                    }else{
                        $('.btn-refresh').click();
                    }
                });
            },
            formatter : {
                map:function(value,row,index){
                    return '<a style="color: #4397fd" href="https://apis.map.qq.com/uri/v1/marker?marker=coord:'+row.lat+','+row.lng+';title:'+row.location+';addr:'+row.location+'&referer=crm" target="_blank" >'+row.location+'</a>';
                }

            }
        }
    };
    return Controller;
});